package zz.test.bluetoothdemo;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Locale;

public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener,View.OnClickListener{

    BluetoothAdapter bluetoothAdapter;
    Switch switchBTState;
    BroadcastReceiver broadcastReceiver;
    Button btnFreshList;
    BluetoothDeviceAdapter adapter;
    ListView listView;
    TextView tvHint;
    final int REQUESTCODE=1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    /**
     * 初始化界面
     * @see BluetoothDeviceAdapter
     */
    private void init() {
        bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();//获取蓝牙适配器Adapter
        switchBTState=findViewById(R.id.switchBluetooth);
        btnFreshList=findViewById(R.id.btnFreshList);
        listView=findViewById(R.id.listView);
        tvHint=findViewById(R.id.tvHint);
        broadcastReceiver=new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {//广播接收器 蓝牙状态切换 或者发现设备时都会发送广播
                if (intent.getAction() != null) {
                    if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {//状态改变
                        int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                        if (state == BluetoothAdapter.STATE_OFF) {//关闭
                            switchBTState.setText(switchBTState.getTextOff());
                            btnFreshList.setEnabled(false);
                        } else if (state == BluetoothAdapter.STATE_ON) {//打开
                            switchBTState.setText(switchBTState.getTextOn());
                            btnFreshList.setEnabled(true);
                        }
                    } else if(intent.getAction().equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)){//启动搜索
                        switchBTState.setEnabled(false);
                        btnFreshList.setEnabled(false);
                        adapter.getDevices().clear();
                        adapter.notifyDataSetChanged();
                        Toast.makeText(MainActivity.this,"正在启动搜索",Toast.LENGTH_LONG).show();
                        if(tvHint.getVisibility()==View.GONE)tvHint.setVisibility(View.VISIBLE);
                    }else if(intent.getAction().equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){//结束搜索
                        switchBTState.setEnabled(true);
                        btnFreshList.setEnabled(true);
                        Toast.makeText(MainActivity.this,String.format(Locale.getDefault(),"搜索结束，共发现%d个设备",adapter.getDevices().size()),Toast.LENGTH_LONG).show();
                    }else if(intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){//发现蓝牙设备
                        if(tvHint.getVisibility()==View.VISIBLE)tvHint.setVisibility(View.GONE);
                        BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        int rssi=intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
                        if(!ContainsDiscoveredDevice(device))
                        adapter.getDevices().add(new FoundDevice(device,rssi));
                        adapter.notifyDataSetChanged();

                    }
                }
            }
        };
        IntentFilter filter=new IntentFilter();//添加事件过滤
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(broadcastReceiver,filter);//注册
        if(bluetoothAdapter==null) {//如果没有蓝牙适配器（例如模拟器）
            Toast.makeText(this, "你的设备不支持蓝牙!", Toast.LENGTH_LONG).show();
            finish();
        }else {
            if (bluetoothAdapter.isEnabled()) {
                switchBTState.setChecked(true);
                btnFreshList.setEnabled(true);
                switchBTState.setText(switchBTState.getTextOn());
            } else {
                switchBTState.setChecked(false);
                btnFreshList.setEnabled(false);
                switchBTState.setText(switchBTState.getTextOff());
            }
            switchBTState.setOnCheckedChangeListener(this);
            btnFreshList.setOnClickListener(this);
            adapter = new BluetoothDeviceAdapter(this);//ListView 适配器
            listView.addHeaderView(View.inflate(this, R.layout.btdeviceheaderlayout, null));
            listView.setAdapter(adapter);
        }
    }

    /**
     * 检查是否已经发现该蓝牙设备
     * @param device 当前蓝牙设备
     * @return 是返回true 否返回false
     */
    private boolean ContainsDiscoveredDevice(BluetoothDevice device) {
        for(FoundDevice d:adapter.getDevices()){
            if(d.getDevice()!=null&&d.getDevice().equals(device))return true;
        }
        return false;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(buttonView==switchBTState){
            if(isChecked){
                bluetoothAdapter.enable();
            }else{
                bluetoothAdapter.disable();
            }
        }
    }

    /**
     * @param v 发生onClick的View
     * @see #checkSelfPermission(String)
     * @see #requestPermissions(String[], int)
     * @see #onRequestPermissionsResult(int,String[],int[])
     */
    @Override
    public void onClick(View v) {
        if(v==btnFreshList){
            //注意：在Android6.0之后的版本中，一些权限需要运行时获取
            if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},REQUESTCODE);//此处将运行到onRequestPermissionsResult函数
            }else{
                StartDiscovery();
            }

        }

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode==REQUESTCODE){
            if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
                StartDiscovery();
            }else{
                Toast.makeText(this,"请授予相关必要权限！",Toast.LENGTH_LONG).show();
            }
        }
    }

    private void StartDiscovery() {
        bluetoothAdapter.startDiscovery();
    }
}
